package com.lzj.task;

import com.lzj.model.Orders;
import com.lzj.service.OrdersService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Lazy;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.DelayQueue;

@Component
@Slf4j
@RequiredArgsConstructor
public class DelayQueueManager implements CommandLineRunner {

    @Resource
    @Lazy
    private OrdersService ordersService;

    private final DelayQueue<Task<Orders>> delayQueue = new DelayQueue<Task<Orders>>();

    private final Set<Integer> ids = new HashSet<>();

    private final DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

    public void put(Task<Orders> task){
        if (ids.contains(task.getOrder().getId())){
            log.info("👉任务添加失败!");
            return;
        }
        ids.add(task.getOrder().getId());
        delayQueue.put(task);
    }

    public boolean remove(Task<Orders> task){
        return delayQueue.remove(task);
    }

    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;


    @Override
    public void run(String... args) throws Exception {
        log.info("初始化延时队列");
        threadPoolTaskExecutor.execute(new Thread(this::executeThread));
    }

    private void executeThread(){
        while (true){
            try {
                Task<Orders> task = delayQueue.take();
                boolean update = ordersService.updateById(task.getOrder());
                if (update){
                    log.info("👉状态更新成功!{}", LocalDateTime.now().format(dateTimeFormat));
                    ids.remove(task.getOrder().getId());
                }
            }catch (InterruptedException e){
                log.error(e.getMessage());
            }
        }
    }
}
